<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="60%"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      autocomplete="off"
      ref="dataForm"
      class="carddPage2"
     
      label-width="120px"
    >
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基本信息" name="first">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="roleName">
                <el-input v-model="dataForm.name" placeholder="姓名"></el-input>
              </el-form-item>

              <el-form-item size="mini" label="职位">
                <el-popover
                  ref="posiPopover"
                  v-model="visibleTree"
                  placement="bottom-start"
                  trigger="click"
                  class="popverg"
                >
                  <el-tree
                    :data="posiList"
                    :props="posiListTreeProps"
                    node-key="menuId"
                    ref="menuListTree"
                    @node-click="roleNodeClick"
                  ></el-tree>
                  <el-input
                    slot="reference"
                    v-model="dataForm.roleName"
                    :readonly="true"
                    placeholder="点击选择"
                    class="menu-list__input"
                  ></el-input>
                </el-popover>
              </el-form-item>

              <el-form-item label="手机号" prop="remark">
                <el-input v-model="dataForm.phone" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="身份证号码" prop="remark">
                <el-input v-model="dataForm.idCard" placeholder="请输入"></el-input>
              </el-form-item>

              <el-form-item label="住址" prop="remark">
                <el-input v-model="dataForm.location" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="remark">
                <el-input v-model="dataForm.passWord" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="卡号">
                <el-input v-model="dataForm.cardStr" placeholder="请输入">
                  <el-button slot="append" @click="getCardStr">生成</el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="照片" class="dragImg">
                <img class="userImg" v-if="dataForm.headPortrait " :src="dataForm.headPortrait " />
                <el-upload
                  class="upload-demo"
                  action="#"
                  :auto-upload="false"
                  accept=".jpg, .jpeg, .png"
                  :on-change="onChange"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :on-remove="handleRemove"
                >
                  <el-button slot="trigger" size="small" type="primary">点击上传</el-button>
                  <el-button
                    style="margin-left:10px"
                    size="small"
                    type="primary"
                    @click="addOrUpdateHandle"
                  >拍照上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1M</div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="人脸识别立柱权限" name="second">
          <div class>
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
            >全选</el-checkbox>
            <el-checkbox-group v-model="checkedlabel" @change="handleCheckedCitiesChange">
              <el-collapse v-model="activeNames">
                <el-collapse-item title="人脸识别" name="1">
                  <el-checkbox
                    border
                    size="medium"
                    v-for="item in antuList"
                    :key="item.id"
                    :label="item.id"
                    v-if="1==item.type"
                    style="margin:5px;width:200px;overflow:hidden"
                  >{{item.name}}</el-checkbox>
                </el-collapse-item>
                <el-collapse-item title="刷卡机" name="2">
                  <el-checkbox
                    border
                    size="medium"
                    v-for="item in antuList"
                    :key="item.id"
                    :label="item.id"
                    v-if="3==item.type"
                    style="margin:5px;width:200px;overflow:hidden"
                  >{{item.name}}</el-checkbox>
                </el-collapse-item>
              </el-collapse>
            </el-checkbox-group>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <TakePhoto v-if="addOrUpdateVisible" ref="addOrUpdate" @saveImgList="setImgUrl" />
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { treeDataTranslate } from "@/utils";
import TakePhoto from "@/components/takePhoto";

export default {
  components: { TakePhoto },

  data() {
    return {
      isIndeterminate: true,
      checkAll: false,
      visible: false,
      visibleTree: false,
      addOrUpdateVisible: false,
      activeNames: ["1"],
      fileList: [],
      activeName: "first",
      posiList: [],
      menuList: [],
      radio1: 0,
      antuList: [],
      checkedlabel: [],
      expendKey: [],
      menuListTreeProps: {
        children: "children",
        label: "name"
      },
      posiListTreeProps: {
        children: "children",
        label: "lable"
      },
      dataForm: {},
      dataRule: {
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }]
      },
      tempKey: -666666 // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
    };
  },
  methods: {
    onChange(file, fileList) {
      const isIMAGE = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isLt1M = file.size / 1024 / 1024;
      if (isIMAGE !== "jpg" && isIMAGE !== "png" && isIMAGE !== "jpeg") {
        this.$message.error("上传文件只能是jpg和png格式!");
        this.fileList.length = 0;
      }
      if (isLt1M > 1) {
        this.$message.error("上传文件大小不能超过 1MB!");
        this.fileList.length = 0;
      }
      let reader = new FileReader(); //html5读文件
      //转BASE64
      reader.readAsDataURL(file.raw);
      reader.onload = e => {
        let base64Str = e.target.result;
        //读取完毕后调用接口
        let imgData = base64Str.split(",")[1];
        console.log(base64Str);
        this.setImgUrl([base64Str]);
      };

      return isIMAGE && isLt1M;
    },
    handleRemove(val, fileList) {},
    beforeAvatarUpload() {},
    init(id) {
      this.dataForm = {
        id: "",
        cardStr: "",
        name: "",
        phone: "",
        roleId: "",
        idCard: "",
        gateIds: "",
        isOut: "0"
      };
      this.dataForm.id = id || "";
      this.$http({
        url: this.$http.adornUrl("/sys/org/list"),
        method: "POST",
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.posiList = data.list;
      });
      this.$http({
        url: this.$http.adornUrl("/sys/employee/info"),
        method: "POST",
        params: this.$http.adornParams({
          id: this.dataForm.id
        })
      }).then(({ data }) => {
        this.antuList = data.gates.filter(
          item => item.type == 1 || item.type == 3
        );
        console.log(this.antuList.length);
        if (data.entity) {
          Object.assign(this.dataForm, data.entity);
          this.fileList = [{ name: "照片", file: data.entity.headPortrait }];
          if (data.entity.gateIds) {
            this.checkedlabel = data.entity.gateIds.split(",");
            this.handleCheckedCitiesChange(this.checkedlabel);
            console.log(this.checkedlabel.length);
          }
        }
      });
      this.visible = true;
    },
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    handleCheckedCitiesChange(data) {
      let checkedCount = data.length;
      this.checkAll = checkedCount === this.antuList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.antuList.length;
    },
    handleCheckAllChange(val) {
      this.checkedlabel = val ? this.antuList.map(item => item.id) : [];
      this.isIndeterminate = false;
    },
    getCardStr() {
      this.$http({
        url: this.$http.adornUrl("/sys/employee/set_card_str"),
        method: "post",
        data: this.$http.adornData()
      }).then(({ data }) => {
        if (data.code == 0) {
          Object.assign(this.dataForm, { cardStr: data.card_str });
        }
      });
    },
    setImgUrl(imgList) {
      this.$http({
        url: this.$http.adornUrl("/sys/employee/upload/img"),
        method: "post",
        data: this.$http.adornData({
          photo: imgList[0].split(";")[1]
        })
      }).then(({ data }) => {
        if (data.code == 0) {
          this.dataForm = Object.assign({}, this.dataForm, {
            headPortrait: data.url
          });
        }
      });
    },
    roleNodeClick(data) {
      if (data.type == "1") {
        Object.assign(this.dataForm, {
          roleId: data.value,
          roleName: data.lable
        });
        this.visibleTree = false;
      }
    },
    handleClick() {},
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sys/employee/update`),
            method: "post",
            data: this.$http.adornData({
              data: JSON.stringify(
                Object.assign(this.dataForm, {
                  gateIds: this.checkedlabel.join(","),
                  isOut: 0
                })
              )
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>
<style  >
.el-popover {
  max-height: 320px;
  overflow-y: auto;
}
.carddPage2 .el-collapse {
  border: none;
}
.carddPage2 .el-collapse-item__header {
  background-color: #f2f2f2;
  margin-top: 5px;
  padding-left: 10px;
  font-weight: 600;
}
</style>
